package com.yanzhu.util;

import com.alibaba.fastjson.JSONObject;
import com.yanzhu.constant.Constant;
import com.yanzhu.constant.Token;
import com.yanzhu.service.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.alibaba.fastjson.JSON.parseObject;


/**
 * @Author: 方炎柱
 * @Description:
 * @Date: Created in 21:41 2018/1/26
 * @Modified:
 */
public class WechatUtil {
    private static Logger logger = LoggerFactory.getLogger(WechatUtil.class);

    public static Token getToken(String code) {
        Token token = new Token();
        String requestUrl = Constant.WX_OPENID_SESSIONKEY_URL.replace("APPID", Constant.APP_ID).replace("SECRET", Constant.APP_SECRET).replace("JSCODE", code);

        HttpUtil httpUtil = new HttpUtil();
        try {

            logger.error(requestUrl);
            HttpResult httpResult = httpUtil.doGet(requestUrl, null, null);

            if(httpResult.getStatusCode() == 200) {
                JSONObject jsonObject = parseObject(httpResult.getBody());
                logger.info("getOpenId: " + jsonObject.toString());
                if(jsonObject.get("errcode") != null) {
                    logger.info("getOpenId returns errcode: " + jsonObject.get("errcode"));
                    return null;
                }else {
//                token.setAccess_token(jsonObject.getString("access_token"));
//                token.setExpiresIn(jsonObject.getInteger("expires_in"));
                    token.setOpenid(jsonObject.getString("openid"));
//                    token.setOpenid(jsonObject.getString("session_key"));
//                    token.setOpenid(jsonObject.getString("js_code"));
//                    token.setOpenid(jsonObject.getString("grant_type"));
//                token.setRefresh_token(jsonObject.getString("refresh_token"));
//                token.setScope(jsonObject.getString("scope"));
//                token.setOpenid("omy8H0dVKofUi52teMZdLCRR5i6s");
                    return token;
                }
            }
        } catch (Exception e) {
            // 获取token失败
            logger.error("获取token失败:");
            e.printStackTrace();
        }
        return null;
    }

    public static User getUserInfo(String openId, String accessToken){
        User user;


        HttpUtil httpUtil = new HttpUtil();
//        JSONObject jsonObject = httpUtil.doGet(url, null, null);
        try {
            String url = Constant.WX_SNSAPI_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
            HttpResult httpResult = httpUtil.doGet(url, null, null);

            if(httpResult.getStatusCode() == 200) {
                JSONObject jsonObject = JSONObject.parseObject(httpResult.getBody());
                logger.info("getOpenId: " + jsonObject.toString());
                if(jsonObject.get("errcode") != null) {
                    logger.info("getOpenId returns errcode: " + jsonObject.get("errcode"));
                    return null;
                } else {
                    logger.error(jsonObject.toJSONString());
                    user = new User();
                    // 用户的标识
                    user.setOpenId(jsonObject.getString("openid"));
                    // 昵称
                    user.setNickname(jsonObject.getString("nickname"));
                    // 性别（1是男性，2是女性，0是未知）
                    user.setGender(jsonObject.getInteger("sex"));
                    // 用户头像
                    user.setAvatar(jsonObject.getString("headimgurl"));
                    // 用户所在国家
                    // user.setCountry(jsonObject.getString("country"));
                    // 用户所在省份
                    //snsUserInfo.setProvince(jsonObject.getString("province"));
                    // 用户所在城市
                    //snsUserInfo.setCity(jsonObject.getString("city"));

                     //提交时间
                    //snsUserInfo.setInputTime(df.format(new Date()));
                    //修改时间
                    //snsUserInfo.setModifyTime(df.format(new Date()));
                    //提交者
                    //snsUserInfo.setInputBy(userId);
                    //修改者
                    //snsUserInfo.setModifyBy(userId);
                    //状态
                    //snsUserInfo.setStatus(1);
                    return user;
                }
                //return httpResult.getBody();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
